/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-6-18 下午6:32 Created by lyyang
 */
package com.xunton.bss.weixin.api.bonus;

import javax.inject.Named;

import com.jade.bss.weixin.WeixinApp;
import com.jade.framework.base.util.HttpUtils;
import com.xunton.bss.weixin.api.WeixinException;
import com.xunton.bss.weixin.api.bonus.request.DeliverBonusRequest;
import com.xunton.bss.weixin.api.bonus.request.QueryRecordRequest;
import com.xunton.bss.weixin.api.bonus.response.DeliverBonusResponse;
import com.xunton.bss.weixin.api.bonus.response.QueryRecordResponse;
import org.apache.http.impl.client.CloseableHttpClient;

//import com.jade.bss.business.bonus.Bonus;
//import com.jade.bss.business.bonus.BonusManager;
//import com.jade.bss.business.bonus.BonusRecord;

/**
 * 红包代理
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-6-18 下午6:32
 */
@Named ("weixin_bonusAgent")
public class BonusAgent
{
    private static final String SEND_BONUS = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
    private static final String GET_BONUS = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";

    private WeixinApp defaultWeixinApp;

    public WeixinApp getDefaultWeixinApp()
    {
        return defaultWeixinApp;
    }

    public void setDefaultWeixinApp(WeixinApp defaultWeixinApp)
    {
        this.defaultWeixinApp = defaultWeixinApp;
    }

    //    protected Log logger = LogFactory.getLog(this.getClass());
    //    private CacheService cacheService;
    //    private String apiKey = "aDdfoi123D093Ilfi900azcjholoaa2Z";
    //    private String cerFilePath = "/jade/yaozb/cer/apiclient_cert.p12";
    //    private String cerFilePassword = "1241808602";
    //    private String mchId = "1241808602";
    //    private String bonusServerIp = "121.40.87.47";
    //    private String wxAppId = "wx6ed3ee6bdcd70fa0";
    //private BonusManager bonusManager;

    //    public static void main(String[] args)
    //    {
    //        BonusAgent agent = new BonusAgent();
    //        agent.setCerFilePath("D:\\temp\\wxpaid\\apiclient_cert.p12");
    //        try {
    //            BonusRecord record = new BonusRecord();
    //            //"1241808602201506260151227640"  "1241808602201507030124150430"
    //            record.setOrderNo("1241808602201507030124150430");
    //            agent.updateRecord(record);
    //        }
    //        catch (Exception ex) {
    //            ex.printStackTrace();
    //        }
    //
    //    }

    //    public String getBonusServerIp()
    //    {
    //        return bonusServerIp;
    //    }
    //
    //    public void setBonusServerIp(String bonusServerIp)
    //    {
    //        this.bonusServerIp = bonusServerIp;
    //    }
    //
    //    public String getWxAppId()
    //    {
    //        return wxAppId;
    //    }
    //
    //    public void setWxAppId(String wxAppId)
    //    {
    //        this.wxAppId = wxAppId;
    //    }
    //
    //    public String getMchId()
    //    {
    //        return mchId;
    //    }
    //
    //    public void setMchId(String mchId)
    //    {
    //        this.mchId = mchId;
    //    }

    //    @Inject
    //    public void setCacheService(@Named ("bonus_cacheService") CacheService cacheService)
    //    {
    //        this.cacheService = cacheService;
    //    }

    //    public BonusManager getBonusManager()
    //    {
    //        return bonusManager;
    //    }
    //
    //    @Inject
    //    public void setBonusManager(@Named ("bss_bonusManager") BonusManager bonusManager)
    //    {
    //        this.bonusManager = bonusManager;
    //    }

    //    public String getApiKey()
    //    {
    //        return apiKey;
    //    }
    //
    //    public void setApiKey(String apiKey)
    //    {
    //        this.apiKey = apiKey;
    //    }
    //
    //    public String getCerFilePath()
    //    {
    //        return cerFilePath;
    //    }
    //
    //    public void setCerFilePath(String cerFilePath)
    //    {
    //        this.cerFilePath = cerFilePath;
    //    }
    //
    //    public String getCerFilePassword()
    //    {
    //        return cerFilePassword;
    //    }
    //
    //    public void setCerFilePassword(String cerFilePassword)
    //    {
    //        this.cerFilePassword = cerFilePassword;
    //    }

    public DeliverBonusResponse sendBonus(WeixinApp weixinApp, DeliverBonusRequest bonusRequest)
            throws WeixinException
    {
        if (weixinApp == null || weixinApp.getMode() == WeixinApp.MODE_PLATFORM) {
            weixinApp = defaultWeixinApp;
        }
        bonusRequest.setClientIp(weixinApp.getServerIp());
        bonusRequest.setMchId(weixinApp.getMerchantId());
        bonusRequest.setWxAppId(weixinApp.getAppId());
        try {
            bonusRequest.calculateSign(weixinApp.getApiKey());
            CloseableHttpClient client = HttpUtils.createP12SSLInsecureClient(weixinApp.getCerFilePath(),
                                                                              weixinApp.getCerFilePassword());
            return HttpUtils.postXmlHttp(client, SEND_BONUS, bonusRequest, DeliverBonusResponse.class);
        }
        catch (Throwable t) {
            throw new WeixinException("err.bss.weixin.api.send_bonus", t.getMessage(), t);
        }
    }

    public QueryRecordResponse getInfo(WeixinApp weixinApp, QueryRecordRequest request)
            throws WeixinException
    {
        try {
            if (weixinApp == null || weixinApp.getMode() == WeixinApp.MODE_PLATFORM) {
                weixinApp = defaultWeixinApp;
            }
            CloseableHttpClient client = HttpUtils.createP12SSLInsecureClient(weixinApp.getCerFilePath(),
                                                                              weixinApp.getCerFilePassword());
            request.setAppId(weixinApp.getAppId());
            request.setMchId(weixinApp.getMerchantId());
            request.calculateSign(weixinApp.getApiKey());
            return HttpUtils.postXmlHttp(client, GET_BONUS, request, QueryRecordResponse.class);
        }
        catch (Throwable t) {
            throw new WeixinException("err.bss.weixin.api.send_bonus", t.getMessage(), t);
        }
    }

    //    public synchronized long luckyDraw(long id, String receivedType, String receivedId)
    //            throws WeixinException
    //    {
    //        logger.info("start luckDraw");
    //        BonusRecord record = new BonusRecord();
    //        record.setBonusId(id);
    //        record.setReceiverId(receivedId);
    //        record.setReceiverType(receivedType);
    //        record.setRecordTime(new Date());
    //        String valueKey = "bonus_values_" + id;
    //        Bonus bonus = bonusManager.get(id);
    //        record.setOwnerType(bonus.getOwnerType());
    //        record.setOwnerId(bonus.getOwnerId());
    //        if (bonus.getQuantity() == 0) {
    //            record.setAmount(0);
    //            record.setStatus(BonusRecord.STATUS_FAILED);
    //            record.setRemark("not_enough_quantity");
    //            bonusManager.addRecord(record);
    //            throw new WeixinException("err.bss.weixin.bonus.not_enough_quantity", "not enough quantity");
    //
    //        }
    //        if (bonusManager.getRecord(id, receivedType, receivedId) != null) {
    //            throw new WeixinException("err.bss.weixin.bonus.already_draw", "bonus has already draw", null, receivedId,
    //                    id);
    //        }
    //        if (!bonus.isLucky()) {
    //            record.setAmount(0);
    //            record.setStatus(BonusRecord.STATUS_SENT);
    //            bonusManager.addRecord(record);
    //            return 0;
    //        }
    //
    //
    //        long[] values = cacheService.get(valueKey);
    //        if (values == null) {
    //            values = bonusManager.generateLuckyDrawer(bonus);
    //            cacheService.set(valueKey, values, 0);
    //        }
    //        int index = values.length - bonus.getQuantity();
    //
    //        long value = values[index];
    //
    //        try {
    //            CloseableHttpClient client = HttpUtils.createP12SSLInsecureClient(cerFilePath, cerFilePassword);
    //            DeliverBonusRequest bonusRequest = new DeliverBonusRequest();
    //            bonusRequest.setActName(bonus.getCampaignName());
    //            bonusRequest.setClientIp(bonusServerIp);
    //            bonusRequest.setMaxValue(value);
    //            bonusRequest.setMchId(mchId);
    //            bonusRequest.setMinValue(value);
    //            bonusRequest.setNickName(bonus.getPublisherName());
    //            bonusRequest.setRemark(bonus.getRemark());
    //            bonusRequest.setReOpenId(receivedId);
    //            bonusRequest.setSendName(bonus.getShopName());
    //            bonusRequest.setTotalAmount(value);
    //            bonusRequest.setWishing(bonus.getWishing());
    //            bonusRequest.setWxAppId(wxAppId);
    //            bonusRequest.calculateSign(apiKey);
    //
    //            DeliverBonusResponse response = HttpUtils.postXmlHttp(client, SEND_BONUS, bonusRequest,
    //                    DeliverBonusResponse.class);
    //            if (response.getReturnCode() != null & response.getReturnCode().equalsIgnoreCase("SUCCESS")) {
    //                record.setOrderNo(bonusRequest.getMchBillNo());
    //                record.setAmount(value);
    //                record.setStatus(BonusRecord.STATUS_SENT);
    //                bonusManager.addRecord(record);
    //                bonusManager.draw(id, value);
    //                if (bonus.getQuantity() == 1) {
    //                    cacheService.delete(valueKey);
    //                }
    //                return value;
    //            }
    //            else {
    //                record.setAmount(0);
    //                record.setStatus(BonusRecord.STATUS_FAILED);
    //                record.setRemark("bonus.api_error");
    //                bonusManager.addRecord(record);
    //                throw new WeixinException("err.bss.weixin.api.send_bonus",
    //                        response.getErrCodeDes() + "," + response.getReturnMsg());
    //            }
    //        }
    //        catch (WeixinException e) {
    //            throw e;
    //        }
    //        catch (Throwable t) {
    //            throw new WeixinException("err.bss.weixin.api.send_bonus", t.getMessage(), t);
    //        }
    //    }
    //
    //    public void updateRecord(BonusRecord record)
    //            throws WeixinException
    //    {
    //        try {
    //            CloseableHttpClient client = HttpUtils.createP12SSLInsecureClient(cerFilePath, cerFilePassword);
    //            QueryRecordRequest request = new QueryRecordRequest();
    //            request.setAppId(wxAppId);
    //            request.setMchId(mchId);
    //            request.setOrderNo(record.getOrderNo());
    //            request.calculateSign(apiKey);
    //            QueryRecordResponse response = HttpUtils.postXmlHttp(client, GET_BONUS, request,
    //                    QueryRecordResponse.class);
    //            if (response.getErrCode() != null && response.getErrCode().equalsIgnoreCase("NOT_FOUND")) {
    //                throw new WeixinException("err.bss.weixin.bonus.not_found", "bonus not found");
    //            }
    //            if (response.getReturnCode() != null & response.getReturnCode().equalsIgnoreCase("SUCCESS")) {
    //                String status = response.getStatus();
    //                if (status.equalsIgnoreCase("FAILED")) {
    //                    bonusManager.updateRecordStatus(record.getId(), BonusRecord.STATUS_FAILED);
    //                }
    //                else if (status.equalsIgnoreCase("RECEIVED")) {
    //                    bonusManager.updateRecordStatus(record.getId(), BonusRecord.STATUS_RECEIVED);
    //                }
    //                else if (status.equalsIgnoreCase("REFUND")) {
    //                    bonusManager.updateRecordStatus(record.getId(), BonusRecord.STATUS_REFUND);
    //                }
    //            }
    //            else {
    //                throw new WeixinException("err.bss.weixin.api.bonus.update_record",
    //                        response.getErrCodeDes() + "," + response.getReturnMsg());
    //            }
    //        }
    //        catch (WeixinException e) {
    //            throw e;
    //        }
    //        catch (Throwable t) {
    //            throw new WeixinException("err.bss.weixin.api.bonus.update_record", t.getMessage(), t);
    //        }
    //    }
}



